/*
 * @Description: 
 * @Author: xiao li
 * @Date: 2021-07-04 00:16:06
 * @LastEditTime: 2022-01-13 15:25:07
 * @LastEditors: xiao li
 */
import Vue from 'vue'
import Vuex from 'vuex'
import test from './modules/test'
import {
  api
} from '@/api'
import router from '@/router'
import Layout from '@/components/layout'
const _import = require('../router/_import_' + process.env.NODE_ENV)

Vue.use(Vuex)

const store = new Vuex.Store({
  // 模块化
  modules: {
    test

  },
  // store数据
  state: {
    show: false,
    isAuth: false,
    routes: []
  },
  getters: {
    show: state => {
      return state.adSwitch
    },
    isAuth: state => {
      return state.isAuth
    },
    routes: state => {
      return state.routes
    }
  },
  mutations: {
    handleShow (state, value) {
      state.show = value
    },
    saveRoutes (state, routes = []) {
      state.routes = routes
      state.isAuth = true
    }
  },
  actions: {
    getUserPromission ({
      commit
    }, obj) {
      if (process.env.NODE_ENV === 'development') {
        commit('saveRoutes', obj.routes)
        routerGo(obj.routes, obj)
      } else {
        // 正式请求接口获取路由
        api.getRoutes().then(res => {
          if (res.code === 200) {
            let allRoutes = [...res.data, {
              path: '*',
              redirect: '/404',
              hidden: true
            }]
            commit('saveRoutes', allRoutes)
            routerGo(allRoutes, obj)
          }
        })
      }
    }
  }
})

export default store

function routerGo (routes, obj) {
  let getRouter = filterAsyncRouter(routes) // 过滤路由
  router.options.routes.push(...getRouter)
  router.addRoutes(getRouter) // 动态添加路由
  // localStorage.setItem('routes', JSON.stringify(getRouter))
  obj.next({ ...obj.to,
    replace: true
  })
}

function filterAsyncRouter (asyncRouterMap) { // 遍历后台传来的路由字符串，转换为组件对象
  const accessedRouters = asyncRouterMap.filter(route => {
    if (route.component) {
      if (route.component === 'Layout') { // Layout组件特殊处理
        route.component = Layout
      } else {
        route.component = _import(route.component)
      }
    }
    if (route.children && route.children.length) {
      route.children = filterAsyncRouter(route.children)
    }
    return true
  })
  return accessedRouters
}
